﻿using Com.Lancetinc.Evs.Data;
using Com.Lancetinc.Evs.Helpers;
using Com.Lancetinc.Evs.Models;
using Com.Lancetinc.Evs.ViewModels;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;

namespace Com.Lancetinc.Evs.Services
{
    public partial class ExperManager
    {
        public const string HistoryRecordDir = "HistoryRecord";
        public const string PictureDir = "Picture";
        public const string ReportDir = "Report";
        public const string DataBaseDir = "DataBase";

        private static ExperManager mExperManager;
        public static ExperManager Default
        {
            get
            {
                if (mExperManager == null)
                {
                    mExperManager = CreateExperManager();
                }
                return mExperManager;
            }
        }

        private static ExperManager CreateExperManager()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            path = Path.Combine(path, DataBaseDir);
            return new ExperManager(path);
        }

        private readonly string mRootDir;
        private readonly string mRecordPath;

        private ExperManager(string rootDir)
        {
            mRootDir = rootDir;
            mRecordPath = Path.Combine(mRootDir, HistoryRecordDir);
            Directory.CreateDirectory(mRecordPath);
        }

        /// <summary>
        /// 取得实验对应的图片和视频存储目录
        /// </summary>
        /// <param name="seqNo"></param>
        /// <returns></returns>
        public string GetExperDataDir(string seqNo)
        {
            return Path.Combine(mRecordPath, seqNo);
        }

        /// <summary>
        /// 取得报告相关目录
        /// </summary>
        /// <param name="seqNo"></param>
        /// <returns></returns>
        public string GetReportDir(string seqNo)
        {
            var expDataDir = GetExperDataDir(seqNo);
            return Path.Combine(expDataDir, ReportDir);
        }

        /// <summary>
        /// 取得图片根目录
        /// </summary>
        /// <param name="seqNo"></param>
        /// <returns></returns>
        public string GetPictureDir(string seqNo)
        {
            var expDataDir = GetExperDataDir(seqNo);
            return Path.Combine(expDataDir, PictureDir);
        }

        public ExperInfo WrapHistoryExper(ExperViewModel exper)
        {
            var experInfo = new ExperInfo(exper)
            {
                WorkDir = GetExperDataDir(exper.SeqNo),
                VideoName = "1.mp4"
            };

            // 兼容老版本（视频格式为wvm）
            if (!File.Exists(experInfo.VideoPath))
            {
                experInfo.VideoName = "1.wvm";
                if (!File.Exists(experInfo.VideoPath))
                {
                    experInfo.VideoName = "1.mp4";
                }
            }

            experInfo.PictureDir = Path.Combine(experInfo.WorkDir, PictureDir);
            if (Directory.Exists(experInfo.PictureDir))
            {
                var imgPaths = Directory.EnumerateFiles(experInfo.PictureDir, "*.jpg");
                foreach (var imgPath in imgPaths)
                {
                    var imgName = Path.GetFileName(imgPath);
                    if (Regex.IsMatch(imgName, @"\d{17}\.jpg"))
                    {
                        experInfo.Images.Add(imgName);
                    }
                }
            }
            return experInfo;
        }

        public ExperInfo CreateExper()
        {
            ExperInfo exper = new ExperInfo();
            exper.Exper.SeqNo = CreateNewSeqNo();
            return exper;
        }

        public void ResetExper(ExperInfo exper)
        {
            exper.Reset();
            exper.Exper.SeqNo = CreateNewSeqNo();
        }

        public string CreateNewSeqNo(string minSeqNo = null)
        {
            var seqNoPrefix = DateTime.Now.ToString("yyyyMMdd");
            var maxSeqNo = AppRepositories.Exper.FindMaxSeqNo(seqNoPrefix);
            string newSeqNo;
            if (string.IsNullOrEmpty(maxSeqNo))
            {
                newSeqNo = seqNoPrefix + "001";
            }
            else
            {
                newSeqNo = (long.Parse(maxSeqNo) + 1).ToString();
            }
            if (!string.IsNullOrEmpty(minSeqNo) && long.Parse(minSeqNo) > long.Parse(newSeqNo))
            {
                newSeqNo = (long.Parse(minSeqNo) + 1).ToString();
            }
            return newSeqNo;
        }

        public string CreateImageName()
        {
            return CreateImageName(DateTime.Now);
        }

        public string CreateImageName(DateTime videoTime)
        {
            return videoTime.ToString("yyyyMMddHHmmssfff") + ".jpg";
        }

        public async Task<bool> DeleteExper(string seqNo)
        {
            // 确定要删除病人信息（包括关联的视频和图片）吗？
            var r = await MessageHelper.ShowYesNoByMsgIdAsync("ExperDetailWindow.ConfirmDeletePatientInfo", Msgs.MsgBox_DeleteConfirm);
            if (r != MessageBoxResult.Yes)
            {
                return false;
            }

            try
            {
                AppRepositories.Exper.DeleteBySeqNo(seqNo);
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError(ex.Message, Msgs.MsgBox_DeleteFailed);
                return false;
            }
            var workDir = GetExperDataDir(seqNo);
            if (Directory.Exists(workDir))
            {
                try
                {
                    Directory.Delete(workDir, true);
                }
                catch
                {
                    MessageHelper.ShowWarning(I18nHelper.Default.GetMessageWithArgs("ExperDetailWindow.DeleteFolderFailed", workDir));
                }
            }

            return true;
        }

        public void InitExperWhenExperStart(ExperInfo exper, short videoWidth, short videoHeight, IInstrumentState ins)
        {
            var dataRoot = GetExperDataDir(exper.Exper.SeqNo);
            while (File.Exists(dataRoot))
            {
                exper.Exper.SeqNo = CreateNewSeqNo(exper.Exper.SeqNo);
                dataRoot = GetExperDataDir(exper.Exper.SeqNo);
            }
            exper.WorkDir = dataRoot;
            exper.PictureDir = Path.Combine(dataRoot, PictureDir);
            Directory.CreateDirectory(exper.PictureDir);
            exper.VideoName = "1.mp4";
            exper.Exper.Exper.StartTime = DateTime.Now.FormatForDbUpdate();
            exper.Exper.Exper.VideoRotationAngle = ins.GetVideoRotationAngle();
            exper.Exper.Exper.VideoWidth = videoWidth;
            exper.Exper.Exper.VideoHeight = videoHeight;
            exper.Exper.Exper.HcSerialNo = ins.HcSerialNo;
            var flipConfig = VideoStartRecordHelper.GetVideoFlipConfig();
            exper.Exper.Exper.FlipHorizontally = flipConfig.FlipHorizontally ? 1 : 0;
            exper.Exper.Exper.FlipVertically = flipConfig.FlipVertically ? 1 : 0;
        }
    }
}
